package com.company.cloud.oss.modules.cloud;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Formatter;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.common.utils.IOUtils;
import com.aliyun.oss.model.GenericResult;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.ProcessObjectRequest;
import com.company.cloud.common.exception.BusinessException;
import com.company.cloud.oss.config.OssConfig;
import com.company.cloud.oss.constant.OssErrorEnum;
import com.company.cloud.oss.modules.cloud.models.ImgInfoModel;
import com.company.cloud.oss.modules.cloud.models.ImgProcess2SaveModel;
import lombok.extern.log4j.Log4j2;

/**
 * 阿里云
 * */
@Log4j2
public class AliyunCloudStorageService extends CloudStorageService{

	private OSS client;
	
	public AliyunCloudStorageService(OssConfig ossConfig) {
		super(ossConfig);
		this.init();
	}
	
	private void init() {
		client= new OSSClientBuilder().build(ossConfig.getEndpoint(),
				ossConfig.getAccessId(), ossConfig.getAccessKey());
	}
	
	private  String getUrl(String path){
	    String domain = "http://" + ossConfig.getBucket() + "." + ossConfig.getEndpoint()+"/";
	    if(!path.startsWith(domain) ) {
	    	path = domain + path;
	    }
	    return path;
	}


	/**
	 * 获取图片信息
	 * */
	@Override
	public ImgInfoModel getImgInfo(String url){
		String httpUrl= this.getUrlAddParam(url,"x-oss-process=image/info");
//		log.debug("++++AliyunCloudStorageService:getImgInfo:url={}",httpUrl);
		String content= HttpUtil.get(httpUrl);
		if(StrUtil.isEmpty(content)){
			throw  new BusinessException(OssErrorEnum.OSS_ImgInfo_Error,"无返回信息");
		}
		if(!JSONUtil.isJson(content)){
			throw  new BusinessException(OssErrorEnum.OSS_ImgInfo_Error,content);
		}
		return JSON.parseObject(content,ImgInfoModel.class);
	}

	/**
	 * 使用不同的图片处理参数处理图片并分别保存为本地图片
	 * */
	public void process2SaveFile(){

	}


	/**
	 * 通过SDK处理图片时,您可以通过ImgSaveAs接口将图片保存至原图片所在存储空间
	 * */
	@Override
	public ImgProcess2SaveModel process2SaveAs(String styleType, String sourceImage, String targetImage) {
		log.info("请求参数:{},{},{}",styleType,sourceImage,targetImage);
		try {
			StringBuilder sbStyle = new StringBuilder();
			Formatter styleFormatter = new Formatter(sbStyle);
			styleFormatter.format("%s|sys/saveas,o_%s,b_%s", styleType,
					BinaryUtil.toBase64String(targetImage.getBytes()),
					BinaryUtil.toBase64String(ossConfig.getBucket().getBytes()));

			log.info("图片处理参数:{}",sbStyle.toString());
			ProcessObjectRequest request = new ProcessObjectRequest(ossConfig.getBucket(), sourceImage, sbStyle.toString());
			GenericResult processResult = client.processObject(request);
			log.info("图片处理后的结果:{}", JSONUtil.toJsonStr(processResult));
			String json = IOUtils.readStreamAsString(processResult.getResponse().getContent(), "UTF-8");
			processResult.getResponse().getContent().close();
			log.info("图片处理后重新保存结果:{}",json);
			client.shutdown();
			return JSON.parseObject(json,ImgProcess2SaveModel.class);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(client!=null) client.shutdown();
		}

		return null;
	}


	@Override
	public String upload(byte[] data, String path) {
		return upload(new ByteArrayInputStream(data), path);
	}

	@Override
	public String uploadSuffix(byte[] data, String suffix) {
		return uploadSuffix(new ByteArrayInputStream(data), suffix);
	}

	@Override
	public String uploadSuffix(InputStream inputStream, String suffix) {
		return upload(inputStream, this.getPath(ossConfig.getDir(), suffix));
	}

	@Override
	public String upload(InputStream inputStream, String path) {
      try {
    	  client.putObject(ossConfig.getBucket(), path, inputStream, null);
    	  client.shutdown();
       } catch (Exception e){
    	   throw new BusinessException(OssErrorEnum.Oss_Upload_File_Error);
      } finally {
		  if(client!=null){ client.shutdown();}
	  }
      return this.getUrl(path);
	}


	@Override
	public void delete(String path) {
		try {
			client.deleteObject(ossConfig.getBucket(), path);
			client.shutdown();
		}catch (Exception e){

		}finally {
			if(client!=null){client.shutdown();}
		}
	}


	

}
